#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os,json,time

class Metric:
    def __init__(self, metric, data_type, value, tags):
        self.metric = metric
        self.data_type = data_type
        self.value = value
        self.tags = tags

class Log:
    time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    def Write(self,Filename,Message):
        Message = str(Message)
        with open(Filename, 'a+') as logs:
            logs.write(Message)

class main():

    while True :
        dic = {}
        time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
        grepNodeManager = "su - hadoop -c '/usr/java/default/bin/jps|grep NodeManager'"
        fileName='/tmp/nm-status.log'
        #hostName = os.popen('hostname').read().strip()
        try : 
            NodeManagerPid = os.popen(grepNodeManager).readline().split()[0]
            grepNodeManagerMem = "cat /proc/%s/status |grep VmRSS" % (NodeManagerPid)
            NodeManagerMen = os.popen(grepNodeManagerMem).readline()
            mes = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) +'\t'+ NodeManagerMen
            Log().Write(fileName,mes)
        except:
            mes= time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "\tNodeManager is down \n"
            Log().Write(fileName,mes)
            restartDn="su - hadoop -c 'yarn-daemon.sh start nodemanager'"
            os.popen(restartDn)
        time.sleep(20)

if __name__ == "__main__":
    main()

